package com.cp.config;


import com.cp.dateformat.CpDateTimeDateFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * Des:
 * 解决前后端 Get/Post请求日期的处理
 *
 * @author XL
 * @Date 2021/8/27 9:29
 */
@Slf4j
@Configuration
@SuppressWarnings("all")
public class CpDateAutoConfiguration {
    /**
     * 默认日期时间格式
     */
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    /**
     * 默认日期格式
     */
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

    /**
     * 默认时间格式
     */
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
    /**
     * 获取当前系统时区
     */
    public static final String TIMEZONE = System.getProperty("user.timezone");

    /**
     * 用于转换RequestParam和PathVariable参数
     * 字符串转化为日期
     */
    @Bean
    public Converter<String, Date> captainDateConverter() {

        Converter<String, Date> converter = new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                CpDateTimeDateFormat format = new CpDateTimeDateFormat();
                try {
                    return StringUtils.isEmpty(source) ? null : format.parse(source.trim());
                } catch (Exception e) {
                    throw new RuntimeException();
                }
            }
        };
        return converter;
    }

    /**
     * Json序列化和反序列化转换器，用于转换Post请求体中的json以及将我们的对象序列化为返回响应的json
     * ObjectMapper基于JsonParser和JsonGenerator来实现JSON实际的读/写
     * 自定义
     */
    @Bean
    public MappingJackson2HttpMessageConverter customizeMappingJackson2HttpMessageConverter() {
        ObjectMapper objectMapper = getObjectMapperInstance();
        doInitObjectMapper(objectMapper);
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);
        return converter;
    }


    /**
     * des:
     * 注册序列化组件
     *
     * @param objectMapper 序列化组件
     * @author captain
     * @date 2022/1/25 13:45
     */
    private void doInitObjectMapper(ObjectMapper objectMapper) {
        initJavaTimeModule(objectMapper);
        initLongToStringModule(objectMapper);
        log.info("成功初始化序列化jackson组件");
    }

    /**
     * des:
     * 获取ObjectMapper实例
     *
     * @return {@link ObjectMapper }
     * @author captain
     * @date 2022/1/25 13:38
     */
    public ObjectMapper getObjectMapperInstance() {
        ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
                .timeZone(TIMEZONE)
                .build();
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        return objectMapper;
    }

    /**
     * des:
     * 序列化将Long变为字符串
     *
     * @return {@link SimpleModule }
     * @author captain
     * @date 2022/1/25 13:42
     */
    public void initLongToStringModule(ObjectMapper objectMapper) {
        SimpleModule longToStringModule = new SimpleModule();
        longToStringModule.addSerializer(Long.class, ToStringSerializer.instance);
        longToStringModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        longToStringModule.addSerializer(long.class, ToStringSerializer.instance);
        objectMapper.registerModule(longToStringModule);
    }

    /**
     * des:
     * 初始化时间序列化 / 反序列化模块
     *
     * @param objectMapper 序列化组件
     * @author captain
     * @date 2022/1/25 13:36
     */
    public void initJavaTimeModule(ObjectMapper objectMapper) {
        // 时间模块
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        //序列化
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
        //反序列化
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));

        //Date序列化
        javaTimeModule.addSerializer(Date.class, new JsonSerializer<Date>() {
            @Override
            public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                CpDateTimeDateFormat formatter = new CpDateTimeDateFormat();
                String formattedDate = formatter.format(date);
                //写
                jsonGenerator.writeString(formattedDate);
            }
        });
        //反序列化
        javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                SimpleDateFormat format = new CpDateTimeDateFormat();
                //读
                String date = jsonParser.getText();
                try {
                    return format.parse(date);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        //注册时间序列化
        objectMapper.setDateFormat(new CpDateTimeDateFormat());
        objectMapper.registerModule(javaTimeModule);
    }
}
